<template>
    <div class="my-collections">
      <h3>我的收藏</h3>
      <PostItem
        v-for="(post, index) in collectedPosts"
        :key="index"
        :post="post"
        :is-admin="isAdmin"
        @collect-post="toggleFavorite"
      />
    </div>
  </template>
  
  <script>
  import PostItem from './PostItem.vue';
  import api from '@/api/api';
  import { mapGetters, mapActions } from 'vuex';
  export default {
    components: {
      PostItem
    },
    data() {
      return {
        collectedPosts: []
      };
    },
    computed: {
      isAdmin() {
        return this.$store.getters.isAdmin;
      },
      ...mapGetters(['getUsername', 'isPostCollected']),
    },
    collectedPosts() {
    return this.$store.state.favorites.map(postId => ({
      id: postId,
      isCollected: true
    }));
  },
    mounted() {
      this.fetchCollectedPosts();
    },
    async created() {
    await this.fetchFavorites();
  },
    methods: {
      fetchCollectedPosts() {
        const username = this.$store.getters.getUsername;
        api.getFavorites(username)
          .then(response => {
            this.collectedPosts = response.data;
          })
          .catch(error => {
            console.error('获取收藏失败:', error);
          });
      },
      toggleFavorite(post) {
        post.isCollected = !post.isCollected;
        const username = this.$store.getters.getUsername;
        if (post.isCollected) {
          api.addFavorite(username, post.id)
            .then(response => {
              this.$message.success('收藏成功');
            })
            .catch(error => {
              console.error('收藏失败:', error);
              this.$message.error('收藏失败，请稍后再试');
            });
        } else {
          api.removeFavorite(username, post.id)
            .then(response => {
              this.$message.success('已取消收藏');
            })
            .catch(error => {
              console.error('取消收藏失败:', error);
              this.$message.error('取消收藏失败，请稍后再试');
            });
        }
      },
      ...mapActions(['fetchFavorites']),
    }
  };
  </script>